<template>
  <div class="goodslist">
    <MyHeader title="商品列表"></MyHeader>
    <MyTable :list="list">
      <template #header>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>

      <!-- 具名插槽 + 作用域插槽一起使用 -->
      <!-- 注意事项: 一个 tempale 上不能有多个 v-slot  -->
      <!-- v-slot:body="scope" -->
      <!-- #body="scope" -->
      <!-- scope:{ row:item } -->
      <!-- <template #body="scope"> -->
      <template #body="{row}">
        <td>{{ row.id }}</td>
        <td>{{ row.goods_name }}</td>
        <td>{{ row.goods_price }}</td>
        <td>
          <input
            @keydown.enter="add(row)"
            @keydown.esc="row.inputValue = ''"
            v-model.trim="row.inputValue"
            @blur="row.inputVisible = false"
            v-focus
            v-if="row.inputVisible"
            type="text"
          />
          <button
            @click="row.inputVisible = true"
            v-else
            class="btn btn-primary btn-sm"
          >
            +Tags
          </button>
          <br />
          <span
            style="margin-right:5px"
            v-for="(item, index) in row.tags"
            :key="index"
            class="badge bg-warning text-dark"
            >{{ item }}</span
          >
        </td>
        <td>
          <button @click="del(row.id)" class="btn btn-danger btn-sm">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
// 导入
import MyHeader from '../components/MyHeader.vue'
import MyTable from '../components/MyTable.vue'

export default {
  components: {
    MyHeader,
    MyTable
  },
  data () {
    return {
      list: []
    }
  },
  async created () {
    // 发起 ajax 请求
    const res = await this.$axios.get('/api/goods')
    // console.log(res.data.data)
    // 数据赋值给 list
    this.list = res.data.data
  },
  methods: {
    del (id) {
      // 找到下标
      let index = this.list.findIndex(item => item.id == id)
      // 删除
      this.list.splice(index, 1)
    },
    add (row) {
      // 非空判断
      if (row.inputValue.length == 0) return alert('输入不能为空！')

      // 添加至 tags 数组
      row.tags.push(row.inputValue)

      // 清空文本框
      row.inputValue = ''
    }
  },
  // 局部自定义指令
  directives: {
    focus: {
      inserted (el) {
        el.focus()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.goodslist {
  padding-top: 45px;
}
</style>
